package com.thermofisher.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class SSLClient
{
    private static final Logger log = LoggerFactory.getLogger(SSLClient.class);

    private static final String HTTP = "http";

    private static final String HTTPS = "https";

    private static SSLConnectionSocketFactory sslsf = null;

    private static PoolingHttpClientConnectionManager cm = null;

    private static SSLContextBuilder builder = null;

    static
    {
        try
        {
            builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(null, new TrustStrategy()
            {
                @Override

                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException
                {
                    return true;
                }

            });
            sslsf = new SSLConnectionSocketFactory(builder.build(),
                                                   new String[] { "SSLv2Hello", "SSLv3", "TLSv1",
                                                           "TLSv1.2" }, null,
                                                   NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslsf)
                    .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static HttpResponse doPost(String url, Map<String, Object> param) throws Exception
    {
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        try
        {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // 设置请求参数
            if (param != null && !param.isEmpty())
            {
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : param.entrySet())
                {
                    //给参数赋值

                    formparams.add(new BasicNameValuePair(entry.getKey(),
                                                          entry.getValue().toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
                                                                                     Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            httpResponse = httpClient.execute(httpPost);
        }
        catch (Exception e)
        {
            log.error("post请求异常：" + e.getMessage() + param);
            throw new RuntimeException(e);
        }
        finally
        {
            if (httpClient != null)
            {
                httpClient.close();
            }
        }
        return httpResponse;
    }

    /**
     *  * httpClient post请求
     *  * @param url 请求url
     *  * @param header 头部信息
     *  * @param param 请求参数 form提交适用
     *  * @param entity 请求实体 json/xml提交适用
     *  * @return 可能为空 需要处理
     *  * @throws Exception
     *  *
     *  
     */

    public static HttpResponse doGet(String url, Map<String, String> header,
                                     Map<String, String> param) throws Exception
    {
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        try
        {
            httpClient = getHttpClient();
            HttpGet httpGet = new HttpGet(url);
            // 设置头信息
            if (header != null && !header.isEmpty())
            {
                for (Map.Entry<String, String> entry : header.entrySet())
                {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置请求参数
            if (param != null && !param.isEmpty())
            {
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : param.entrySet())
                {
                    //给参数赋值
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
                                                                                     Consts.UTF_8);
                String str = EntityUtils.toString(urlEncodedFormEntity);
                httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
            }
            log.info("======url==========" + httpGet.getURI());
            httpResponse = httpClient.execute(httpGet);
        }
        catch (Exception e)
        {
            log.error("post请求异常：" + e.getMessage() + param);
            throw new RuntimeException(e);
        }
        finally
        {
            if (httpClient != null)
            {
                httpClient.close();
            }
        }
        return httpResponse;
    }

    public static CloseableHttpClient getHttpClient() throws Exception
    {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .setConnectionManagerShared(true)
                .build();
        return httpClient;
    }

    public static String readHttpResponse(HttpResponse httpResponse)
            throws ParseException, IOException

    {
        StringBuilder builder = new StringBuilder();
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        builder.append("status:" + httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext())
        {
            builder.append("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null)
        {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:" + responseString.length());
            builder.append("response content:" + responseString.replace("\r\n", ""));
        }
        return builder.toString();
    }
}
